package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单业务层实现类
 */
@Service
public class OrderServiceImpl implements OrderService {
    /**
     * 地址簿
     */
    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 购物车
     */
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 订单
     */
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 订单明细
     */
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    /**
     *  websocket
     */
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 商家地址
     */
    @Value("${sky.shop.address}")
    private String shopAddress;

    /**
     * 百度地图应用ak(秘钥)
     */
    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 获取用户的地址信息
        AddressBook addressBook = this.addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        // 判断地址是否为空，为空不进行下面的操作
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // TODO --检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        // 获取用户的购物车信息
        ShoppingCart shoppingCart = new ShoppingCart();
        // 当前登录用户
        shoppingCart.setUserId(BaseContext.getCurrentId());
        // 购物车列表
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        // 购物车判断,如果购物车没有数据,代表下单也没有要购买的商品
        if (CollectionUtils.isEmpty(list)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 组装主表订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        // 订单状态 待付款
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        // 用户Id
        orders.setUserId(BaseContext.getCurrentId());
        // 订单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付状态 未支付
        orders.setPayStatus(Orders.PAID);
        // 当前登录用户
//        orders.setUserName();
        // 手机号
        orders.setPhone(addressBook.getPhone());
        // 地址信息
        orders.setAddress(addressBook.getDetail());
        // 收货人
        orders.setConsignee(addressBook.getConsignee());
        // 新增订单
        this.orderMapper.insert(orders);
        // 组装订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 从购物车获取订单明细
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            // 赋值订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        // 保存订单明细
        this.orderDetailMapper.insert(orderDetailList);
        // 删除购物车
        this.shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        // 返回给前端的响应值
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        // 订单id
        orderSubmitVO.setId(orders.getId());
        // 订单号
        orderSubmitVO.setOrderNumber(orders.getNumber());
        // 订单金额
        orderSubmitVO.setOrderAmount(orders.getAmount());
        // 订单时间
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        // 来单提醒
        Map map = new HashMap();
        // 消息类型
        map.put("type",1);
        // 订单id
        map.put("orderId",orders.getId());
        // 消息内容
        map.put("content","订单号：" +orders.getNumber());
        // 通过WebSocket实现来单提醒，向客户端浏览器推送消息
        this.webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return orderSubmitVO;
    }

    /**
     * 查询历史订单
     */
    @Override
    public PageResult pageOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 设置用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        // 查询订单
        Page<Orders> ordersPage = this.orderMapper.pageOrders(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 判断是否查询到订单
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            // 查询到了订单
            for (Orders order : ordersPage) {
                // 调用mapper层获取对应订单的订单明细
                List<OrderDetail> orderDetails = this.orderDetailMapper.getByOrderId(order.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                // 将订单信息添加到集合里
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 根据订单id查询订单详情
     */
    @Override
    public OrderVO getById(Long id) {
        // 包装为Orders类
        Orders orders = new Orders();
        // 设置订单id
        orders.setId(id);
        // 调用mapper查询该订单id的订单信息
        Orders order = this.orderMapper.getById(id);
        // 调用mapper查询该订单id的订单明细信息
        List<OrderDetail> orderDetailList = this.orderDetailMapper.getByOrderId(id);
        // 创建OrderVO对象
        OrderVO orderVO = new OrderVO();
        //  order ----> orderVO
        BeanUtils.copyProperties(order, orderVO);

        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 根据订单id修改订单状态
     */
    @Override
    public void cancelOrders(Long id) {
        // 插叙该订单
        Orders orders = this.orderMapper.getById(id);
        // 判断是否存在该订单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断该订单的状态，已接单不能取消 已接单：3
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 判断订单是否为待接单状态，待接单状态需要退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // TODO-退款功能
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
//            //支付状态修改为 退款
//            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        // 订单状态 Orders.CANCELLED: 已取消
        orders.setStatus(Orders.CANCELLED);
        // 取消原因
        orders.setCancelReason("用户已取消");
        // 取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 调用mapper层
        this.orderMapper.update(orders);
    }

    /**
     * 再来一单
     */
    @Override
    public void repetition(Long id) {
        // 获取订单明细信息
        List<OrderDetail> orderDetailList = this.orderDetailMapper.getByOrderId(id);
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 创建购物车对象集合
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        // 遍历订单明细信息
        for (OrderDetail orderDetail : orderDetailList) {
            // 将每个订单明细对象copy给购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            // 给购物车设置用户id
            shoppingCart.setUserId(userId);
            // 给购物车设置创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 将购物车对象提添加到集合中
            shoppingCartList.add(shoppingCart);
        }
        // 批量添加购物车信息
        this.shoppingCartMapper.insertShooppingCartList(shoppingCartList);
    }

    /**
     * 管理端获取订单列表
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 查询订单
        Page<Orders> ordersPage = this.orderMapper.pageOrders(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 判断是否查询到订单
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            // 查询到了订单
            for (Orders order : ordersPage) {
                // 调用mapper层获取对应订单的订单明细
                List<OrderDetail> orderDetails = this.orderDetailMapper.getByOrderId(order.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                String orderDishes = "";
                // 遍历订单明细集合
                for (OrderDetail orderDetail : orderDetails) {
                    String jsonString = JSONObject.toJSONString(orderDetail);
                    orderDishes += orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
                }
                // 将拼接后的订单明细给orderVO
                orderVO.setOrderDishes(orderDishes);
                // 将订单信息添加到集合里
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 查询各状态的订单数量
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        // 待接单
        Integer toBeConfirmed = this.orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        // 待派送
        Integer confirmed = this.orderMapper.countStatus(Orders.CONFIRMED);
        // 派送中
        Integer deliveryInProgress = this.orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 订单接单
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 创建Orders对象
        Orders orders = new Orders();
        // 订单id
        orders.setId(ordersConfirmDTO.getId());
        // 订单状态
        orders.setStatus(Orders.CONFIRMED);
        // 修改订单信息
        this.orderMapper.update(orders);
    }

    /**
     * 订单拒单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 查询订单是否存在
        Orders order = this.orderMapper.getById(ordersRejectionDTO.getId());
        // 判断订单是否存在
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        // 创建Orders对象
        Orders orders = new Orders();
        // 订单id
        orders.setId(ordersRejectionDTO.getId());
        // 订单状态
        orders.setStatus(Orders.CANCELLED);
        // 订单拒绝原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        // 订单取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 修改订单信息
        this.orderMapper.update(orders);
    }

    /**
     * 取消订单
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 查询订单是否存在
        Orders order = this.orderMapper.getById(ordersCancelDTO.getId());
        // 判断订单是否存在
        if (order == null || order.getStatus() >= Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == 1) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        // 创建Orders对象
        Orders orders = new Orders();
        // 订单id
        orders.setId(ordersCancelDTO.getId());
        // 订单状态
        orders.setStatus(Orders.CANCELLED);
        // 订单取消订单原因
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        // 订单取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 修改订单信息
        this.orderMapper.update(orders);
    }

    /**
     * 派送订单
     */
    @Override
    public void delivery(Long id) {
        // 查询订单是否存在
        Orders order = this.orderMapper.getById(id);
        // 判断订单是否存在
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        // 创建Orders对象
        Orders orders = new Orders();
        // 订单id
        orders.setId(id);
        // 订单状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        // 修改订单信息
        this.orderMapper.update(orders);
    }

    /**
     * 完成订单
     */
    @Override
    public void complete(Long id) {
        // 查询订单是否存在
        Orders order = this.orderMapper.getById(id);
        // 判断订单是否存在
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        // 创建Orders对象
        Orders orders = new Orders();
        // 订单id
        orders.setId(id);
        // 订单状态
        orders.setStatus(Orders.COMPLETED);
        // 订单送达时间
        orders.setDeliveryTime(LocalDateTime.now());
        // 修改订单信息
        this.orderMapper.update(orders);
    }

    /**
     *  用户催单
     */
    @Override
    public void reminder(Long id) {
        // 获取订单信息
        Orders orders = this.orderMapper.getById(id);
        // 判断订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 催单提醒
        // 数据封装
        Map map = new HashMap();
        // 类型
        map.put("type",2);   // 催单提醒
        // 订单id
        map.put("orderId",id);
        // 提醒内容
        map.put("content","订单号：" + orders.getNumber());
        // 通过WebSocket实现来单提醒，向客户端浏览器推送消息
        this.webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     */
    private void checkOutOfRange(String address) {
        Map<String, String> map = new HashMap<>();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        // 获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺解析失败");
        }

        // 数据解析
        // 获取返回的结果
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        // 获取经度值
        String lat = location.getString("lat");
        // 获取维度值
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        // 获取收货地址经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        // 数据解析
        // 获取返回的结果
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        // 获取经度值
        lat = location.getString("lat");
        // 获取维度值
        lng = location.getString("lng");
        //用户经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");
        // 路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        // 数据解析
        JSONObject resultStr = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) resultStr.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        // 判断路线是否超过5000米
        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
